import datetime

from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _

from bootstrap_datepicker_plus import TimePickerInput

from .models import LabLog, ShiftSchedule, StationDataLog

'''
==============================================================
ShiftSchedule
==============================================================
'''


class ShiftScheduleModelForm(forms.ModelForm):
    '''
    默认创建值班表的Form
    按月批量创建时调用
    '''

    class Meta:
        model = ShiftSchedule
        fields = ('duty_date', 'arrange_duty_person',)
        widgets = {'duty_date': forms.TextInput(attrs={'readonly': True}),
                   'arrange_duty_person': forms.Select(), }


class SignInForm(forms.ModelForm):
    '''
    值班签到调用的Form
    '''

    class Meta:
        model = ShiftSchedule
        fields = ('duty_date', 'actual_duty_person',)
        widgets = {'duty_date': forms.HiddenInput(),
                   'actual_duty_person': forms.HiddenInput(), }


class ChangeSignInForm(forms.ModelForm):
    '''
    换班签到调用的Form
    '''

    class Meta:
        model = ShiftSchedule
        fields = ('duty_date', 'actual_duty_person',)
        widgets = {'duty_date': forms.HiddenInput(),
                   'actual_duty_person': forms.Select(), }


'''
================================================================
Lablog
================================================================
'''


# class MyTimePickerInput(TimePickerInput):
#     template_name = 'logs/my-time-picker.html'


class LabLogModelForm(forms.ModelForm):
    # log_time = forms.TimeField(
    #     label='记录时间',
    #     widget=TimePicker(
    #         options={
    #         },
    #         attrs={
    # 'autocomplete': 'off',
    # 'input_toggle': False,
    # 'icon_toggle': True,
    # 'append': 'fa fa-clock-o',
    # },
    # ),
    # )

    class Meta:
        model = LabLog
        fields = ('weather', 'log_time', 'lab_template', 'lab_humidity',
                  'hc_room_template', 'hc_room_humidity', 'network_delay',
                  'packet_lose_rate', 'description')
        widgets = {
            'log_time': TimePickerInput(
                options={
                    'format': 'HH:mm',
                },
                # attrs={
                #     'css_class': 'input-group date',
                #     'field_class': 'input-group date',
                #     'div.css_class': 'input-group date',
                # }
            )
        }

    def __init__(self, *args, **kwargs):
        self.log_date = kwargs.pop('log_date')
        self.time_slot = kwargs.pop('time_slot')
        self.is_sign_in = kwargs.pop('is_sign_in')
        super(LabLogModelForm, self).__init__(*args, **kwargs)

        if self.time_slot == 1:
            self.fields['log_time'].initial = datetime.time(9, 0, 0)
        elif self.time_slot == 2:
            self.fields['log_time'].initial = datetime.time(21, 0, 0)

    def clean_log_time(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        time_slot = self.time_slot
        log_date = self.log_date
        log_time = cleaned_data.get('log_time')
        log_datetime = datetime.datetime.combine(log_date, log_time)
        morning_time_begin = datetime.time(hour=0, minute=0, second=0)
        morning_time_end = datetime.time(hour=12, minute=0, second=0)

        afternoon_time_begin = morning_time_end
        afternoon_time_end = morning_time_begin

        morning_begin = datetime.datetime.combine(log_date, morning_time_begin)
        morning_end = datetime.datetime.combine(log_date, morning_time_end)
        afternoon_begin = morning_end
        afternoon_end = datetime.datetime.combine(log_date + datetime.timedelta(days=1), afternoon_time_end)

        now = datetime.datetime.now()

        if time_slot == 1 and (log_datetime < morning_begin or log_datetime >= morning_end):
            raise ValidationError(
                _('上午日志时间在%(morning_time_begin)s至%(morning_time_end)s(不含%(morning_time_end)s)之间'),
                code='invalid',
                params={'morning_time_begin': morning_time_begin, 'morning_time_end': morning_time_end}
            )
        if time_slot == 2 and (log_datetime < afternoon_begin or log_datetime >= afternoon_end):
            raise ValidationError(
                _('下午日志时间在%(afternoon_time_begin)s至次日%(afternoon_time_end)s(不含%(afternoon_time_end)s)之间'),
                code='invalid',
                params={'afternoon_time_begin': afternoon_time_begin,
                        'afternoon_time_end': afternoon_time_end}

            )
        if log_datetime > now:
            raise ValidationError('现在时间是：{}，你穿越了吗？'.format(datetime.datetime.strftime(now, '%Y-%m-%d %H:%M')))

        return self.cleaned_data.get('log_time')

    def clean_network_delay(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        network_delay = cleaned_data.get('network_delay')
        if network_delay <= 0:
            raise ValidationError('网络延迟的数值范围应大于0')
        return self.cleaned_data.get('network_delay')

    def clean_lab_template(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        lab_template = cleaned_data.get('lab_template')
        min_template = -20
        max_template = 40
        if lab_template < min_template or lab_template > max_template:
            raise ValidationError(
                _('机房温度在%(min_template)s-%(max_template)s°之间)'),
                code='invalid',
                params={'min_template': min_template, 'max_template': max_template}
            )
        return self.cleaned_data.get('lab_template')

    def clean_lab_humidity(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        lab_humidity = cleaned_data.get('lab_humidity')
        min_humidity = 0
        max_humidity = 90
        if lab_humidity <= min_humidity or lab_humidity > max_humidity:
            raise ValidationError(
                _('机房湿度在%(min_humidity)s-%(max_humidity)s%%RH之间(不包含%(min_humidity)s%%HR)'),
                code='invalid',
                params={'min_humidity': min_humidity, 'max_humidity': max_humidity}
            )
        return self.cleaned_data.get('lab_humidity')

    def clean_hc_room_template(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        hc_room_template = cleaned_data.get('hc_room_template')
        min_template = -20
        max_template = 40
        if hc_room_template < min_template or hc_room_template > max_template:
            raise ValidationError(
                _('人机交互室温度在%(min_template)s-%(max_template)s°之间)'),
                code='invalid',
                params={'min_template': min_template, 'max_template': max_template}
            )
        return self.cleaned_data.get('hc_room_template')

    def clean_hc_room_humidity(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        hc_room_humidity = cleaned_data.get('hc_room_humidity')
        min_humidity = 0
        max_humidity = 90
        if hc_room_humidity <= min_humidity or hc_room_humidity > max_humidity:
            raise ValidationError(
                _('机房湿度在%(min_humidity)s-%(max_humidity)s%%RH之间(不包含%(min_humidity)s%%HR)'),
                code='invalid',
                params={'min_humidity': min_humidity, 'max_humidity': max_humidity}
            )
        return self.cleaned_data.get('hc_room_humidity')

    def clean_packet_lose_rate(self):
        cleaned_data = super(LabLogModelForm, self).clean()
        packet_lose_rate = cleaned_data.get('packet_lose_rate')
        if packet_lose_rate < 0 or packet_lose_rate > 100:
            raise ValidationError('掉包率的数值范围在0-100之间')
        return self.cleaned_data.get('packet_lose_rate')

    def clean(self):
        cleaned_data = super(LabLogModelForm, self).clean()

        is_sign_in = self.is_sign_in
        if not is_sign_in:
            self.add_error(None, "未签到，请先签到!")

        return cleaned_data


'''
==============================================================
StationDataLog
==============================================================
'''


class StationDataLogModelForm(forms.ModelForm):
    class Meta:
        model = StationDataLog
        fields = ('station', 'log_date',
                  'online_interrupt_start', 'online_interrupt_end',
                  'online_interrupt_duration',
                  'description')
        widgets = {'station': forms.HiddenInput(),
                   'log_date': forms.HiddenInput(),
                   'online_interrupt_start': forms.TextInput(attrs={'data-datepicker': 'datepicker', }),
                   'online_interrupt_end': forms.TextInput(attrs={'data-datepicker': 'datepicker', }),
                   }

    def __init__(self, *args, **kwargs):
        is_auto = kwargs.pop('is_auto')
        super(StationDataLogModelForm, self).__init__(*args, **kwargs)
        if is_auto == 1:
            self.fields['online_interrupt_start'].widget.attrs['readonly'] = True
            self.fields['online_interrupt_end'].widget.attrs['readonly'] = True
            self.fields['online_interrupt_duration'].widget.attrs['readonly'] = True
